package com.example.login.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.dtos.ResponseResult;
import com.example.login.entity.Employee;
import com.example.login.entity.dto.EmployeeDto;
import com.example.login.mapper.EmployeeMapper;
import com.example.login.service.EmployeeService;
import com.example.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.utils.RedisConstants.*;

@Service
@Transactional
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResponseResult getEmployee(Employee employee) {
        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        //password = DigestUtils.md5DigestAsHex(password.getBytes());

        //先通过redis获取用户 如果有直接登入

        //2、根据页面提交的用户名username查询数据库
        Employee emp = employeeMapper.selectEmployee(employee.getUsername());
        //3、如果没有查询到则返回登录失败结果
        if (emp == null){
            return ResponseResult.errorResult(500,"登录失败");
        }
        //4、密码比对，如果不一致则返回登录失败结果
        if (!emp.getPassword().equals(password)){
            return ResponseResult.errorResult(500,"登录失败");
        }
        System.out.println("============");
        //7.保存用户信息到redis
        //7.1s随机生成token作为登入令牌
        String token = UUID.randomUUID().toString(true);
        //7.2 将user对象转为HashMap存储
        EmployeeDto employeeDto = BeanUtil.copyProperties(emp, EmployeeDto.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(employeeDto,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()));
        //7.3存储
        String tokenKey = LOGIN_Employee_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        //7.4 设置token有效期
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.MINUTES);
        System.out.println("============");
        UserHolder.saveEmployeeDto(employeeDto);
        return ResponseResult.success(employeeDto,token);
    }

    /**
     * 退出
     *
     * @return
     */
    @Override
    public void logout() {

    }

    /**
     * 查询员工信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public ResponseResult<Page> pageInfo(Integer page, Integer pageSize, String name) {
        Page<Employee> page1 = new Page(page, pageSize);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Employee::getName, name);
        queryWrapper.eq(Employee::getIsDelete,1);
        Page<Employee> employeePage = this.page(page1, queryWrapper);
        return ResponseResult.okResult(employeePage);
    }

    /**
     * 添加员工
     *
     * @param employee
     * @return
     */
    @Override
    public ResponseResult addEmployee(Employee employee) {
        employeeMapper.insert(employee);
        return ResponseResult.okResult("添加员工成功") ;
    }

    /**
     * 数据回显
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult employee(Long id) {
        Employee employee = employeeMapper.selectById(id);
        return ResponseResult.okResult(employee);
    }

    /**
     * 修改状态
     *
     * @param id@return
     */
    @Override
    public ResponseResult updateStatus(Long id) {
        Employee employee = employeeMapper.selectById(id);
        if (!employee.getStatus()) {
            employee.setStatus(true);
        } else {
            employee.setStatus(false);
        }
        employeeMapper.updateById(employee);
        return ResponseResult.okResult(employee);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public ResponseResult deleteEmployees(Long[] ids) {
        for (Long id : ids) {
            Employee employee = this.getById(id);
            Boolean status = employee.getStatus();
            if (status){
                return ResponseResult.errorResult(500,"员工信息状态正常不能删除");
            }
            LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Employee::getId, id);
            updateWrapper.set(Employee::getIsDelete, 0);
            this.update(updateWrapper);
        }
        return ResponseResult.okResult("员工信息删除成功");
    }


}
